package cn.dglydrpy.study.j2ee.kafka.consumer;


import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import cn.dglydrpy.study.j2ee.kafka.entity.User;
import cn.dglydrpy.study.j2ee.kafka.serialization.UserDeserializer;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
/**
 * Kafka默认提供了反序列化的接口：org.apache.kafka.common.Deserializer
 * 
 * 提供的实现有：
 * ByteArrayDeserializer
 * ByteBufferDeserializer
 * BytesDeserializer
 * DoubleDeserializer
 * FloatDeserializer
 * IntegerDeserializer
 * StringDeserializer
 * LongDeserializer
 * ShortDeserializer
 * 可通过实现Deserializer自定义反序列化器
 * @author LY_飘涯
 *
 */
public class MyKafkaUserConsumer {

    public static void main(String[] args) {
        Map<String, Object> configs = new HashMap<>();
        configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.80.131:9092");
        configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 设置自定义的反序列化器
        configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, UserDeserializer.class);

        configs.put(ConsumerConfig.GROUP_ID_CONFIG, "user_consumer");
        configs.put(ConsumerConfig.CLIENT_ID_CONFIG, "consumer_id");
        configs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        KafkaConsumer<String, User> consumer = new KafkaConsumer<String, User>(configs);

        // 订阅主题
        consumer.subscribe(Collections.singleton("tp_user"));

        final ConsumerRecords<String, User> records = consumer.poll(Long.MAX_VALUE);

        records.forEach(new Consumer<ConsumerRecord<String, User>>() {
            @Override
            public void accept(ConsumerRecord<String, User> record) {
            	User user = record.value();
            	
                System.out.println("userId:" + user.getUserId() + " username:" + user.getUsername());
            }
        });

        // 关闭消费者
        consumer.close();

    }

}
